
package com.afd.ozblip.activity;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.StringUtil;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class AddVipActivity extends BaseActivity {

    /****************** 视图变量 **************************/
    private RadioGroup sexRg;
    private RadioButton manRb;
    private RadioButton womanRb;
    private EditText nameEt;
    private EditText birthDayEt;
    private Button submitBtn;
    /****************** 数据变量 **************************/
    private String businessId;
    private String vipId;
    private Integer sex;
    private String nameStr;
    private String birthDayStr;
    public static String fileName = "OZBLIP_VIP";
    private Map<String, Object> resultMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_vip);
        // 启动返回功能
        toBack();
        // 寻找视图
        findViews();
        // 设置监听
        setListeners();
        // 获取参数
        getBundle();
    }

    /**
     * 寻找视图
     */
    public void findViews() {
        this.sexRg = (RadioGroup) findViewById(R.id.rg_add_vip_sex);
        this.manRb = (RadioButton) findViewById(R.id.rb_add_vip_man);
        this.womanRb = (RadioButton) findViewById(R.id.rb_add_vip_woman);
        this.nameEt = (EditText) findViewById(R.id.et_add_vip_name);
        this.birthDayEt = (EditText) findViewById(R.id.et_add_vip_birthday);
        this.birthDayEt.setFocusable(false);
        this.submitBtn = (Button) findViewById(R.id.btn_add_vip_submit);
        // 获取上次保留的卡信息
        SharedPreferences settings = getSharedPreferences(fileName,
                Context.MODE_PRIVATE);
        String vipName = settings.getString("vip_name", null);
        int vipSex = settings.getInt("vip_sex", -1);
        String vipBirth = settings.getString("vip_birth", null);
        nameEt.setText(vipName);
        if (vipSex != -1) {
            sex = vipSex;
            if (vipSex == 1) {
                manRb.setChecked(true);
            } else {
                womanRb.setChecked(true);
            }
        }
        birthDayEt.setText(vipBirth);
    }

    /**
     * 设置监听
     */
    public void setListeners() {
        View.OnClickListener addVipClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_more_layout_setting:
                        Intent settingIntent = new Intent(AddVipActivity.this,
                                SettingActivity.class);
                        startActivity(settingIntent);
                        break;
                    case R.id.et_add_vip_birthday:
                        Calendar c = Calendar.getInstance();
                        birthDayStr = birthDayEt.getText().toString();
                        DatePickerDialog dialog = new DatePickerDialog(
                                AddVipActivity.this,
                                new DatePickerDialog.OnDateSetListener() {
                                    public void onDateSet(DatePicker dp, int year,
                                            int month, int dayOfMonth) {
                                        birthDayEt.setText(year + "-" + (month + 1)
                                                + "-" + dayOfMonth);
                                    }
                                }, c.get(Calendar.YEAR), // 传入年份
                                c.get(Calendar.MONTH), // 传入月份
                                c.get(Calendar.DAY_OF_MONTH) // 传入天数
                        );
                        if (!StringUtil.isNullOrEmpty(birthDayStr)) {
                            String[] dateArr = birthDayStr.split("-");
                            if (dateArr.length == 3) {
                                dialog = new DatePickerDialog(AddVipActivity.this,
                                        new DatePickerDialog.OnDateSetListener() {
                                            public void onDateSet(DatePicker dp,
                                                    int year, int month,
                                                    int dayOfMonth) {
                                                birthDayEt.setText(year + "-"
                                                        + (month + 1) + "-"
                                                        + dayOfMonth);
                                            }
                                        }, Integer.valueOf(dateArr[0]), // 传入年份
                                        Integer.valueOf(dateArr[1]) - 1, // 传入月份
                                        Integer.valueOf(dateArr[2]) // 传入天数
                                );
                            }
                        }

                        dialog.show();
                        break;
                    case R.id.btn_add_vip_submit:
                        if (commonUserInfo == null) {
                            showLoginDialog();
                        } else {
                            nameStr = nameEt.getText().toString();
                            birthDayStr = birthDayEt.getText().toString();
                            if (verifyData()) {
                                // 存储当前卡信息，方便下一次添加
                                SharedPreferences settings = getSharedPreferences(
                                        fileName, Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = settings.edit();
                                editor.putString("vip_name", nameStr);
                                editor.putInt("vip_sex", sex);
                                editor.putString("vip_birth", birthDayStr);
                                editor.commit();
                                requestAddVipData();
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        };
        this.birthDayEt.setOnClickListener(addVipClick);
        this.submitBtn.setOnClickListener(addVipClick);
        this.sexRg
                .setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        switch (checkedId) {
                            case R.id.rb_add_vip_man:
                                sex = 1;
                                break;
                            case R.id.rb_add_vip_woman:
                                sex = 0;
                                break;

                            default:
                                break;
                        }

                    }
                });
    }

    /**
     * 获取传递的参数
     */
    private void getBundle() {
        Intent intent = getIntent();
        businessId = intent.getStringExtra("businessId");
        vipId = intent.getStringExtra("vipId");
    }

    /**
     * 验证数据
     */
    private boolean verifyData() {
        if (StringUtil.isNullOrEmpty(nameStr)) {
            showLongToast(this, "请填写姓名", true);
            return false;
        }
        if (sex == null) {
            showLongToast(this, "请选择性别", true);
            return false;
        }
        if (StringUtil.isNullOrEmpty(birthDayStr)) {
            showLongToast(this, "请填写生日", true);
            return false;
        }
        return true;
    }

    /**
     * 获取添加VIP数据
     */
    private void requestAddVipData() {
        if (StringUtil.isNullOrEmpty(businessId)) {
            return;
        }
        if (StringUtil.isNullOrEmpty(vipId)) {
            return;
        }
        if (commonUserInfo == null) {
            return;
        }
        AsyncLoadData ald = new AsyncLoadData(this, "提交中...",
                new AsyncAction() {

                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> addReviewParamMap = new HashMap<String, Object>();
                        addReviewParamMap.put("sellerId", businessId);
                        addReviewParamMap.put("userId",
                                commonUserInfo.getUserId());
                        addReviewParamMap.put("vipId", vipId);
                        addReviewParamMap.put("userName", nameStr);
                        addReviewParamMap.put("userSex", sex);
                        addReviewParamMap.put("userBirthday", birthDayStr);

                        // 发送请求
                        byte[] commentItemList = HttpUtil.requestByPost(
                                AddVipActivity.this, Constants.ADD_VIP_API,
                                addReviewParamMap);
                        if (commentItemList != null) {
                            resultMap = new ParseJson()
                                    .parseAddResultJson(commentItemList);
                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        boolean returnFlg = (Boolean) resultMap
                                .get("returnFlg");
                        String resultMsg = resultMap.get("regMessage")
                                .toString();
                        if (returnFlg) {
                            showShortToast(mContext, resultMsg, true);
                            finish();
                        } else {
                            System.out.println(resultMsg);
                            showShortToast(mContext, resultMsg, true);
                        }
                    }

                });
        ald.execute(0);

    }
}
